/**
 * 
 */
package org.vsg.stock.dzh;

import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.vsg.common.configration.PropertiesSupport;
import org.vsg.stock.extension.service.StockMigrationService;


/**
 * @author vison
 *
 */
public class StockDailyLineInput {

	private final static Logger logger = LoggerFactory.getLogger(StockDailyLineInput.class);	

	static private DateFormat format = new SimpleDateFormat("yyyy-MM-dd");	
	
	public void exec(ApplicationContext appContext , Date date) throws Exception {
		
		PropertiesSupport proSupport = (PropertiesSupport)appContext.getBean("propertyConfigurer");
		
		String propDailyLIne = proSupport.getProperties().getProperty("stock.dailyline.dir");
		if (propDailyLIne == null) {
			logger.info("Property 'stock.dailyline.dir' is not defined! ");
		}
		
		File parentDir = new File(propDailyLIne);
		
		
		File dailyFile = new File(parentDir , format.format(date) +".txt");
	
		StockMigrationService stockMigrationService = (StockMigrationService)appContext.getBean("stockMigrationService");
		
		stockMigrationService.updateDailyLine(dailyFile);


	}
	
	

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Calendar cale = Calendar.getInstance();

		// --- get the from date and to date ---
		Date date = cale.getTime();		
		for (String arg : args) {
			if (arg.startsWith("-DrefDate=")) {
				String dateString = arg.replaceFirst("-DrefDate=", "").trim();
				try {
					date = format.parse( dateString );
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}

		}
		
		ClassLoader clsLoader = StockDailyLineInput.class.getClassLoader();
		// --- run the main page ---
		// build the read the path , dzh's home path
		String[] configContextFiles = {
				"classpath:/spring/configurationContext.xml",
				"classpath*:/spring/applicationContext.xml",
				"classpath*:/spring/dataAccessContext.xml"
		};
		
		ApplicationContext ctx = new ClassPathXmlApplicationContext(configContextFiles,true);
		
	
		StockDailyLineInput mainProg = new StockDailyLineInput();
		
		try {
			mainProg.exec(ctx ,date);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		logger.info("program run ... Ok!");
		



	}

}
